package com.xd.case1;

import org.apache.zookeeper.*;

import java.io.IOException;

public class DistributeServer {

    private String connectString = "zookeeper1:2181,zookeeper2:2181,zookeeper3:2181";
    private int sessionTimeout = 2000000000;

    private ZooKeeper zk = null;
    private String parentNode = "/servers";


    public static void main(String[] args) {
        DistributeServer server = new DistributeServer();

        try {
            //创建到zookeeper客户端的连接
            server.getConnection();

            //注册服务器（注册服务器就是创建节点）
            server.registerServer(args[0]);

            //业务功能
            server.business(args[0]);

        } catch (IOException e) {
            e.printStackTrace();
        } catch (InterruptedException e) {
            e.printStackTrace();
        } catch (KeeperException e) {
            e.printStackTrace();
        }

    }

    private void business(String hostName) throws InterruptedException {
        System.out.println(hostName + " is working");
        Thread.sleep(Long.MAX_VALUE);
    }

    private void registerServer(String hostname) throws InterruptedException, KeeperException {
        //服务器相对zookeeper集群来说是一个客户端，他创建的节点是临时的带序号的
        String create = zk.create(parentNode + "/" + hostname, hostname.getBytes(), ZooDefs.Ids.OPEN_ACL_UNSAFE, CreateMode.EPHEMERAL_SEQUENTIAL);
        System.out.println(hostname + " is online");
    }

    private void getConnection() throws IOException {
        zk = new ZooKeeper(connectString, sessionTimeout, new Watcher() {
            @Override
            public void process(WatchedEvent watchedEvent) {

            }
        });
    }


}
